﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SharePointApp3Web.Pages.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>tasks365</title>  
        <script src="../Scripts/jquery-2.0.0.min.js"> </script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
        <script   type="text/javascript"  src="//code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
        <link href="//code.jquery.com/ui/1.10.3/themes/cupertino/jquery-ui.css"  rel="stylesheet"/>      
        <script src="../Scripts/jquery-ui.custom.js"></script>   
        <link href="../Content/fullcalendar.css" rel="stylesheet" /> 
        <script src="../Scripts/fullcalendar.min.js"></script>    
        <script   type="text/javascript"  src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
        <script type="text/javascript" src="_layouts/15/sp.runtime.js"> </script>
        <script type="text/javascript" src="_layouts/15/sp.js"> </script>
        <script type="text/javascript" src="../Script/UXScript.js"> </script>
        <link href="../Content/jquery.qtip.css" rel="stylesheet" />
        <script src="../Scripts/jquery.qtip.js"> </script>
        <script type="text/javascript">

            var ctx;
            var web;
            var lists;
            var hostweburl;
            var appweburl;
            var crmTaskUrl;
            var executor;
            var arrayOfTaskType = ["CRM"];
            var taskListTitleArray;
            var userEmailId;
            var userIdForTask;
            var arrayOfEvents = [];
            var csharpArraryOfEvents = [];

            // the new event created in select
            var newEvent = new Object();

            // Load the required SharePoint libraries.
            $(document).ready(function () {

                var myJsonString = document.getElementById("hiddenObject").value;
                var myTaskTypeString = document.getElementById("hiddenTaskType").value;
                userIdForTask = document.getElementById("hiddenSharePointUserId").value;
                crmTaskUrl = document.getElementById("hiddenCrmTaskUrl").value;


                csharpArraryOfEvents = eval("(" + myJsonString + " ) ");
                taskListTitleArray = eval("(" + myTaskTypeString + " ) ");

                var combo = document.getElementById("taskType");
                for (var k = 0; k < taskListTitleArray.length; k++) {
                    var option = document.createElement("option");
                    option.text = taskListTitleArray[k].listName;
                    option.value = taskListTitleArray[k].listEntityTypeFullName;
                    try {
                        combo.add(option, null); //Standard 
                    } catch (error) {
                        combo.add(option); // IE only
                    }
                }


                //Get the URI decoded URLs.
                hostweburl = decodeURIComponent(
                getQueryStringParameter("SPHostUrl"));
                appweburl = decodeURIComponent(
                getQueryStringParameter("SPAppWebUrl"));

                // Resources are in URLs in the form:
                // web_url/_layouts/15/resource
                var scriptbase = hostweburl + "/_layouts/15/";


                $.getScript(scriptbase + "SP.RequestExecutor.js");

                // load the qtip for showing tool tip
                var tooltip = $('<div/>').qtip({
                    id: 'fullcalendar',
                    prerender: true,
                    content: {
                        text: ' ',
                        title: {
                            text: 'Task Details'
                        }
                    },
                    position: {
                        my: 'top right',
                        at: 'bottom right',
                        target: 'event',
                        viewport: $(window)
                    },

                    style: {
                        classes: 'qtip-light qtip-tipped'
                    }
                }).qtip('api');


                // load the calendar
                $('#fullcalendar').fullCalendar({
                    editable: true,
                    height: 700,
                    droppable: true,
                    theme: true,
                    selectable: true,
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    weekmode: 'liquid',
                    eventMouseover: function (data, event, view) {
                        var content = '<b>' + data.title + '</b>' + '<p><b>Start: </b>' + data.start + '<br/>' + '<p><b>End: </b>' + data.end + '<br/>' + '<p><b>Priority: </b>' + data.priority + '<br/>' + '<p><b>Description: </b> ' + data.description + '</p>' + '<p><b>Task List: </b> ' + data.taskListName + '</p>';


                        tooltip.set({
                            'content.text': content
                        }).reposition(event).show(event);
                    },

                    eventMouseout: function (data, event, view) {
                        tooltip.hide();
                    },

                    eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc) {


                        if (confirm("Confirm move?")) {


                            UpdateEvent(event, dayDelta);
                        } else {
                            revertFunc();
                        }
                    },

                    eventClick: function (calEvent, jsEvent, view) {

                        window.open(calEvent.taskUrl);

                    },

                    eventResize: function (event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
                        if (confirm("Confirm resize?")) {

                            UpdateEvent(event, dayDelta);
                        } else {
                            revertFunc();
                        }

                    },
                    selectHelper: true,
                    select: function (start, end, allDay) {

                        $("#eventToAdd").dialog({
                            title: "Add Task",
                            modal: true,
                            buttons: {
                                "Add": function () {


                                    var startDate = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
                                    var endDate = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");


                                    var eventToSave = new Object();
                                    eventToSave.EventID = Math.floor(200 * Math.random());

                                    newEvent.start = eventToSave.StartDate = startDate;
                                    newEvent.end = eventToSave.EndDate = endDate;
                                    newEvent.title = eventToSave.EventName = $("#eventToAdd #eventName").val();
                                    newEvent.taskListName = eventToSave.TaskName = $("#eventToAdd #taskType option:selected").text();
                                    newEvent.type = eventToSave.TaskTypeName = $("#eventToAdd #taskType option:selected").val();
                                    newEvent.priority = eventToSave.TaskPriority = $("#eventToAdd #priorityType option:selected").val();
                                    newEvent.description = eventToSave.Description = $("#eventToAdd #eventDescription").val();
                                    newEvent.allDay = allDay;


                                    if (eventToSave.TaskName == "CRM") {

                                        // create a crm task call a page method
                                        newEvent.color = '#3A79B8';
                                        newEvent.taskUrl = crmTaskUrl;
                                        newEvent.listEntityTypeFullName = '';
                                        var parameters = ["taskTitle", eventToSave.EventName, "startDate", eventToSave.StartDate, "dueDate", eventToSave.EndDate, "description", eventToSave.Description, "priority", eventToSave.TaskPriority];
                                        // for CRM Task
                                        PageMethod("CreateTaskInCRM", parameters, succeededInsert, failedInsert);

                                    } else {

                                        // it is sharepoint task call the create listitem method
                                        // Initialize the RequestExecutor with the app web URL.
                                        executor = new SP.RequestExecutor(appweburl);


                                        // for priority
                                        if (eventToSave.TaskPriority == "High") newEvent.priority = eventToSave.TaskPriority = "(1) High";
                                        else if (eventToSave.TaskPriority == "Normal") newEvent.priority = eventToSave.TaskPriority = "(2) Normal";
                                        else if (eventToSave.TaskPriority == "Low") newEvent.priority = eventToSave.TaskPriority = "(3) Low";

                                        newEvent.color = 'slategray';
                                        newEvent.listEntityTypeFullName = eventToSave.TaskTypeName;

                                        var fieldUserValues = new Array();
                                        fieldUserValues.push(userIdForTask);

                                        var item = {
                                            "__metadata": {
                                                "type": eventToSave.TaskTypeName
                                            },
                                            "Title": eventToSave.EventName,
                                            "StartDate": startDate,
                                            "DueDate": endDate,
                                            "Body": eventToSave.Description,
                                            "Priority": eventToSave.TaskPriority,
                                            'AssignedToId': {
                                                "results": fieldUserValues
                                            },
                                        };


                                        executor.executeAsync({
                                            url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + eventToSave.TaskName + "')/items?@target='" + hostweburl + "'",
                                            method: "POST",
                                            headers: {
                                                "accept": "application/json;odata=verbose",
                                                "content-type": "application/json;odata=verbose",
                                                "X-RequestDigest": $("#__REQUESTDIGEST").val()

                                            },
                                            body: JSON.stringify(item),
                                            success: function (data) {


                                                succeededInsert(data);


                                            },
                                            error: failedInsert
                                        });
                                    }


                                }
                            }
                        });

                    },


                    dayClick: function () {
                        tooltip.hide();
                    },
                    eventResizeStart: function () {
                        tooltip.hide();
                    },
                    eventDragStart: function () {
                        tooltip.hide();
                    },
                    viewDisplay: function () {
                        tooltip.hide();
                    },
                    events: csharpArraryOfEvents,
                    eventRender: function (event, element) {
                        //prepare the data for dropping as external item
                        element.data('eventObject', event);
                    }
                });


                // for deleting tasks
                $('#fullcalendar').children('.fc-content').after('<div id="calendarTrash" style="float: right; padding-top: 5px; padding-right: 5px; padding-left: 5px;"><img src="../Images/Tasks-Metro-icon.png" alt="Task Complete"/></div>');

                $("#calendarTrash").droppable({
                    tolerance: 'pointer',
                    drop: function (event, ui) {

                        var originalEventObject = ui.draggable.data('eventObject');

                        if (ui.helper) {
                            var event = originalEventObject;
                            var answer = confirm("Mark Task As Complete?");
                            if (answer) {

                                $('#fullcalendar').fullCalendar('removeEvents', event.id);

                                DeleteEvent(event);
                            }
                        }
                    }
                });


                // for chrome
                //Get the DisplayType from url parameters
                var displayType = decodeURIComponent(getQueryStringParameter('DisplayType'));

                //Get the URI decoded SharePoint site url from the SPHostUrl parameter.
                var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

                //Build absolute path to the layouts root with the spHostUrl
                var layoutsRoot = spHostUrl + '/_layouts/15/';

                //Execute the correct script based on the displayType
                if (displayType == 'FullScreen') {
                    //Load the SP.UI.Controls.js file to render the App Chrome
                    $.getScript(layoutsRoot + 'SP.UI.Controls.js', renderSPChrome);
                } else if (displayType == 'iframe') {
                    //Create a Link element for the defaultcss.ashx resource
                    var linkElement = document.createElement('link');
                    linkElement.setAttribute('rel', 'stylesheet');
                    linkElement.setAttribute('href', layoutsRoot + 'defaultcss.ashx');

                    //Add the linkElement as a child to the head section of the html
                    var headElement = document.getElementsByTagName('head');
                    headElement[0].appendChild(linkElement);
                }

                // end of chrome

            });


            function renderSPChrome() {
                //Get the host site logo url from the SPHostLogoUrl parameter
                var hostlogourl = decodeURIComponent(getQueryStringParameter('SPHostLogoUrl'));

                //Set the chrome options for launching Help, Account, and Contact pages
                var options = {
                    'appIconUrl': hostlogourl,
                    'appTitle': 'Tasks 365'
                };

                //Load the Chrome Control in the divSPChrome element of the page
                var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
                chromeNavigation.setVisible(true);
            }


            // Function to retrieve a query string value.
            // For production purposes you may want to use
            // a library to handle the query string.

            function getQueryStringParameter(paramToRetrieve) {


                var params = document.URL.split("?")[1].split("&");
                var strParams = "";
                for (var i = 0; i < params.length; i = i + 1) {
                    var singleParam = params[i].split("=");
                    if (singleParam[0] == paramToRetrieve) return singleParam[1];
                }
            }


            function UpdateEvent(event, delta) {


                var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
                var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");

                if (event.type != 'CRM') {

                    // Initialize the RequestExecutor with the app web URL.
                    executor = new SP.RequestExecutor(appweburl);

                    var item = {
                        "__metadata": {
                            "type": event.listEntityTypeFullName
                        },
                        "StartDate": start,
                        "DueDate": end
                    };


                    executor.executeAsync({
                        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + event.taskListName + "')/items(" + event.id + ")?@target='" + hostweburl + "'",
                        method: "POST",
                        headers: {
                            "accept": "application/json;odata=verbose",
                            "content-type": "application/json;odata=verbose",
                            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                            "X-HTTP-Method": "MERGE",
                            "If-Match": "*"
                        },
                        body: JSON.stringify(item),
                        success: function (data) {
                            succeededAjaxFn(data);
                        },
                        error: failedAjaxFn
                    });

                } else {


                    var parameters = ["taskGuid", event.id, "startDate", start, "dueDate", end];
                    // for CRM Task
                    PageMethod("UpdateTaskInCRM", parameters, succeededAjaxFn, failedAjaxFn);
                }

            }


            function DeleteEvent(event) {

                if (event.type != 'CRM') {

                    // Initialize the RequestExecutor with the app web URL.
                    executor = new SP.RequestExecutor(appweburl);

                    var item = {
                        "__metadata": {
                            "type": event.listEntityTypeFullName
                        },
                        "Status": "Completed"
                    };


                    executor.executeAsync({
                        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + event.taskListName + "')/items(" + event.id + ")?@target='" + hostweburl + "'",
                        method: "POST",
                        headers: {
                            "accept": "application/json;odata=verbose",
                            "content-type": "application/json;odata=verbose",
                            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                            "X-HTTP-Method": "MERGE",
                            "If-Match": "*"
                        },
                        body: JSON.stringify(item),
                        success: function (data) {
                            succeededAjaxFn(data);
                        },
                        error: failedAjaxFn
                    });

                } else {


                    var parameters = ["taskGuid", event.id];
                    // for CRM Task
                    PageMethod("SetStateTaskInCRM", parameters, succeededDelete, failedAjaxFn);
                }


            }


            var succeededDelete = function (result) {


            };
            var succeededInsert = function (result) {

                var newlyCreatedTaskId;
                var taskUrl;
                if (newEvent.type != 'CRM') {

                    // get the id $.parseJSON(data.body);.d.Id
                    taskUrl = hostweburl + "/Lists/" + newEvent.taskListName + "/DispForm.aspx?ID=" + $.parseJSON(result.body).d.ID;
                    newlyCreatedTaskId = $.parseJSON(result.body).d.ID;
                } else {

                    taskUrl = newEvent.taskUrl + result.d;
                    newlyCreatedTaskId = result.d;
                }


                $('#fullcalendar').fullCalendar('renderEvent', {
                    id: newlyCreatedTaskId,
                    title: newEvent.title,
                    start: newEvent.start,
                    end: newEvent.end,
                    allDay: newEvent.allDay,
                    color: newEvent.color,
                    description: newEvent.description,
                    priority: newEvent.priority,
                    taskListName: newEvent.taskListName,
                    type: newEvent.type,
                    taskUrl: taskUrl,
                    listEntityTypeFullName: newEvent.listEntityTypeFullName

                }, true // make the event "stick"
                );

                $("#eventToAdd").dialog("close");


                // reset the event dialog
                $("#eventToAdd #eventName").val("");
                $("#eventToAdd #taskType").prop('selectedIndex', 0);
                $("#eventToAdd #priorityType").prop('selectedIndex', 0);
                $("#eventToAdd #eventDescription").val("");

            };

            var failedInsert = function (result) {

            };


            var succeededAjaxFn = function (result) {


            };

            var failedAjaxFn = function (result) {


            };


            function PageMethod(fn, paramArray, successFn, errorFn) {
                var pagePath = window.location.pathname;

                //-------------------------------------------------------------------------+
                // Create list of parameters in the form:                                  |
                // {"paramName1":"paramValue1","paramName2":"paramValue2"}                 |
                //-------------------------------------------------------------------------+
                var paramList = '';
                if (paramArray.length > 0) {
                    for (var i = 0; i < paramArray.length; i += 2) {
                        if (paramList.length > 0) paramList += ',';
                        paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
                    }
                }
                paramList = '{' + paramList + '}';
                //Call the page method
                $.ajax({
                    type: "POST",
                    url: pagePath + "/" + fn,
                    contentType: "application/json; charset=utf-8",
                    data: paramList,
                    dataType: "json",
                    success: successFn,
                    error: errorFn
                });
            }
     
        </script>

        <style>

            body {
		
                font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
                font-size: 14px;
                text-align: center;
            }

            #fullcalendar {
                margin: 0 auto;
                width: 70%;
            }


        </style>

    </head>
    <body>
        <form id="form1" runat="server">

            <!-- Chrome control placeholder -->
            <div id="divSPChrome">
            </div>
       
            <asp:Label ID="Label1" runat="server" Text="Label" Font-Size="Small"></asp:Label>
          
            <div id='fullcalendar'></div>
         
       
        </form>
    
        <p>

            <input id="hiddenObject" type="hidden" runat="server" />
            <input id="hiddenTaskType" type="hidden" runat="server" />
            <input id="hiddenSharePointUserId" type="hidden" runat="server" />
            <input id="hiddenCrmTaskUrl" type="hidden" runat="server" />
      
        </p>
        
        <div id="eventToAdd" style="display: none; font-size: 12px;" >
        <table>
            <tr><td> Task name:</td><td align="left"><input id="eventName" type="text" /></td></tr>
            <tr><td>   Task Type :</td><td align="left"> <select id="taskType"></select></td></tr>
            <tr><td> Priority :</td><td align="left"> 
                                        <select id="priorityType">
                                            <option value="High">High</option>
                                            <option value="Normal">Normal</option>
                                            <option value="Low">Low</option>
                                        </select></td></tr>
            <tr><td> Description:</td><td align="left"><textarea id="eventDescription" rows="4" cols="20"></textarea></td></tr>
        </table>

    </body>
</html>